package com.aracky.common.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @author zengzhiping
 * @Description: 转换工具类
 * @date 2021-07-14
 */
public class ConvertUtil {

    private static Logger logger = LoggerFactory.getLogger(ConvertUtil.class);

    /**
     * 复制单个对象
     * @param source
     * @param target
     * @param <T>
     * @return
     */
    public static <T> T sourceToTarget(Object source, Class<T> target) {
        if (source == null) {
            return null;
        }
        T targetObject = null;
        try {
            targetObject = target.newInstance();
            BeanUtils.copyProperties(source, targetObject);
        } catch (Exception e) {
            logger.error("convert error ", e);
        }
        return targetObject;
    }

    /**
     * 复制多个对象
     * @param sourceList
     * @param target
     * @param <T>
     * @return
     */
    public static <T> List<T> sourceToTargets(Collection<?> sourceList, Class<T> target) {
        if (sourceList == null) {
            return null;
        }
        List targetList = new ArrayList<>(sourceList.size());
        try {
            for (Object source : sourceList) {
                T targetObject = target.newInstance();
                BeanUtils.copyProperties(source, targetObject);
                targetList.add(targetObject);
            }
        } catch (Exception e) {
            logger.error("convert error ", e);
        }
        return targetList;
    }
}
